<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Base_Twitter extends Controller_Base_OAuth {

	protected $provider = 'twitter';

	public function action_index() {
		if ($this->token AND $this->token->name === 'access') {
			Request::current()->redirect($this->request->uri(array('action' => 'verify')));
		} else {
			$this->response->body(HTML::anchor($this->request->uri(array('action' => 'login')), 'Login with Twitter'));
		}
	}

	public function action_setmail() {
		$twitter_id = $this->request->post("twitter_id");
		$email = $this->request->post("email");
		$name = $this->request->post("name");

		try {
			// create a new user
			$user = ORM::factory("user");
			$password = text::random("alnum", 8);
			$user->create_user(array("email" => $email,
				"name" => $name,
				"password" => $password,
				"password_confirm" => $password,
					), array('email', 'name', 'password')
			);

			// add the relationship with the user role
			$user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find());

			// send email with the new user password
			Email::send($user->email, "Conta", "Sua senha é: " . $password);

			// associate the user with the extern account login
			$twitterLogin = ORM::factory("twitter_login")->values(array('twitter_id' => $twitter_id, 'users_id' => $user->id));
			$twitterLogin->save();
			Auth::instance()->force_login($user);
			Request::current()->redirect("/");
		} catch (ORM_Validation_Exception $e) {
			$this->response->body(Json_View::factory(array("content" => $e->errors())));
		} catch (Exception $e) {
			$errors = array("email" => $e->getMessage());
			$this->response->body(Json_View::factory(array("content" => $errors)));
		}
	}

	public function action_verify() {
		$response = $this->demo_account_verify_credentials();
		$twitterId = $response->status->id;
		$name = $response->name;
		$twitterLogin = ORM::factory("twitter_login", array('twitter_id' => $twitterId));

		// user do not exists so redirects to register email view
		if ("" != $twitterLogin) {
			Auth::instance()->force_login($twitterLogin->users);
			Request::current()->redirect("/");
		} else {
			$this->view->content = Smarty_View::factory("twitterEmail.tpl");
			$this->view->content->twitter_id = $twitterId;
			$this->view->content->name = $name;
			$this->response->body($this->view);
		}
	}

	public function demo_account_verify_credentials() {
		$api = Twitter::factory('account');
		$response = $api->verify_credentials($this->consumer, $this->token);
		return $response;
	}

} // End OAuth_Twitter